//
//  GGDownLoadViewController.m
//  GGDFU
//
//  Created by 陈志勇 on 17/1/14.
//  Copyright © 2017年 陈志勇. All rights reserved.
//

#import "GGDownLoadViewController.h"
#import "GGDFUProtocol.h"
#import "GGBaseInfoData.h"
#import "BLECentralManager.h"
#import "GGMD5.h"
#import "GGBLEManager.h"
#import <SVProgressHUD.h>

typedef NS_ENUM(NSInteger, GGDFUDownLoadStep)
{
    GGDFUDownLoadStepReset = 0,     ///< 重启单片机
    GGDFUDownLoadStepShakehand,     ///< 握手
    GGDFUDownLoadStepDownLoad,      ///< 下载
    GGDFUDownLoadStepComplete,      ///< 下载完成
};

@interface GGDownLoadViewController () <UITextViewDelegate>
/** 下载的协议 */
@property(strong,nonatomic) GGDFUProtocol *sendingDataModel;
/** 下载的步骤 */
@property(assign,nonatomic) GGDFUDownLoadStep step;
/**  下载的文件路径 */
@property(copy,nonatomic) NSString *filePath;
/**  下载的文件  */
@property(strong,nonatomic) NSData *fileData;
/** 下载的包编号 */
@property(assign,nonatomic) NSUInteger packetIndex;
/** 下载完成 */
@property(assign,nonatomic,getter = isInfoDataDownloadComplete) BOOL infoDataDownloadComplete;
/** 数据发送成功 */
@property(assign,nonatomic,getter = isSendDataSuccess) BOOL sendDataSuccess;
/** 定时器 */
@property(strong,nonatomic) NSTimer *timer;
/** 下载的次数 */
@property(assign,nonatomic) NSUInteger downloadCount;
/** 上一次发送的数据 */
@property(strong,nonatomic) NSData *previousData;
/** 第一次数据下载 */
@property(assign,nonatomic,getter = isFirstDownload) BOOL firstDownload;


@property (weak, nonatomic) IBOutlet UIButton *downLoadBtn;
@property (weak, nonatomic) IBOutlet UITextView *debugTextView;

@end

@implementation GGDownLoadViewController

#pragma mark - init
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpDebugTextView];
    
//    [self beginDelegate];
    
    self.packetIndex = 1;
    self.downloadCount = 0;
    self.sendDataSuccess = NO;
    
    [[GGBLEManager getInstance] connectInfoReturn:^(CBCentralManager *central, CBPeripheral *peripheral, NSString *stateStr) {
        if ([stateStr isEqualToString:@"DISCONNECT"]) {
            [self.navigationController popViewControllerAnimated:YES];
        };
    }];
}

- (void)setUpDebugTextView
{
    self.debugTextView.editable = NO;
    self.debugTextView.layoutManager.allowsNonContiguousLayout = false;
    self.debugTextView.delegate = self;
    self.debugTextView.text = nil;
}

#pragma mark - Action

- (IBAction)downloadBtnClk{
    
    self.firstDownload = YES;
    
    // 取出文件路径，如果路径为空则跳出
    self.filePath = [[NSBundle mainBundle] pathForResource:@"ChaXinSuoJHB_LanYa_GSJMXYV2_10" ofType:@"bin"];
    if ([_filePath isEqualToString: @""]) {
        [SVProgressHUD showInfoWithStatus:@"没有文件可以下载"];
        return;
    }
    
    // 应用握手
    NSData *data  = [GGDFUProtocol reset];
    [[GGBLEManager getInstance] sendMsgWithSubPackage:data];
    self.previousData = data;
    self.downloadCount++;
    [self addText:@"程序开始下载..."];
    [self checkResposnData];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(reSendData) userInfo:nil repeats:YES];
    
    self.downLoadBtn.enabled = NO;
    self.step = GGDFUDownLoadStepReset;
    
    
//    [[BLECentralManager shareInstance].getFirstConnector sendData:data];
    
//    self.step = GGDFUDownLoadStepReset;
//    [self beginDelegate];
//    self.downLoadBtn.enabled = NO;
}

#pragma mark - 数据处理

- (void)checkResposnData
{
    [[GGBLEManager getInstance] responseReturn:^(NSData *responseData){
        
        // 收到数据就清楚计时器和下载次数
        [self clearTimerAndDownloadCount];
        
        // 如果是应用握手则不需要判断协议头及校验和
        if (self.step != GGDFUDownLoadStepReset) {
            /**
             *  解析收到的蓝牙数据头尾及校验和
             */
            Byte *responseByte = (Byte *)[responseData bytes];
            
            NSUInteger length = [responseData length];
            // 判断协议头是否正确
            if (responseByte[0] != 0xaa || responseByte[length - 1] != 0x3c) {
                [SVProgressHUD showErrorWithStatus:@"协议头、尾错误"];
                return ;
            }
            [self addText:@"协议头尾正确"];
            
            // 判断校验和是否正确
            if (![GGDFUProtocol parseSumWithResponseData:responseData]) {
                [SVProgressHUD showErrorWithStatus:@"校验和错误"];
                return;
            }
            [self addText:@"校验和正确"];
        }
    
        
        switch (self.step) {
            case GGDFUDownLoadStepReset:
            {
                NSString *tempStr = [GGDFUProtocol dataTohexString:responseData];
                if ([tempStr isEqualToString:@"7e3230303144303030453030324638464431340d"]) {
                
                    [self addText:@"应用握手成功"];
                    /**
                     *  应用握手成功后，需要发送引导握手命令，需要把文件路径传进去
                     */
                    NSData *tempData = [GGDFUProtocol shakeHandWithFilePath:self.filePath];
                    self.fileData = [NSData dataWithContentsOfFile:self.filePath]; // 加载文件数据
                    NSLog(@"引导握手命令:%@",tempData);
                    // 发送协议命令
                    [[GGBLEManager getInstance] sendMsgWithSubPackage:tempData];
                    self.downloadCount++;
                    self.sendDataSuccess = NO;
                    self.previousData = tempData;
                    [self resumeTimer];
                    
                    // 返回数据进入下一步
                    self.step = GGDFUDownLoadStepShakehand;
                }else{
                    [self addText:@"返回数据错误-->应用握手失败"];
                }
                
                
            }
                break;
            case GGDFUDownLoadStepShakehand:
            {
                // 解析返回的数据
                NSData *infoData = [GGDFUProtocol parseInfoData:responseData];
                NSUInteger packetIndex = [GGDFUProtocol parseInfoDataPacketIndex:infoData];
                BOOL isSucceed = [GGDFUProtocol parseCommandResult:infoData];
                
                NSLog(@"包编号:%zd ---执行结果:%zd",packetIndex,isSucceed);
                // 握手成功，进入下一步，否者跳出
                if (packetIndex != 0 || isSucceed == NO) {
                    [self addText:@"引导握手失败"];
                    return;
                }
                [self addText:@"引导握手成功,开始数据块下载"];
                
                // 发送数据块
                [self sendDowloadInfoData];
                
                // 进入下一步
                self.step = GGDFUDownLoadStepDownLoad;
            }
                break;
            case GGDFUDownLoadStepDownLoad:
            {
                // 解析返回的数据
                NSData *infoData = [GGDFUProtocol parseInfoData:responseData];
                NSUInteger packetIndex = [GGDFUProtocol parseInfoDataPacketIndex:infoData];
                BOOL isSucceed = [GGDFUProtocol parseCommandResult:infoData];
                
                NSLog(@"包编号:%zd ---执行结果:%zd",packetIndex,isSucceed);
                // 握手成功
                if (packetIndex != _packetIndex || isSucceed == NO) {
                    NSString *tempStr = [NSString stringWithFormat:@"下载包编号%zd失败,返回的包编号为%zd",_packetIndex,packetIndex];
                    [self addText:tempStr];
                    
                    // 如果是第一次下载，则需要取出错误的包编号，并重新开始
                    if (self.isFirstDownload){
                        self.packetIndex = packetIndex;
                        // 重新开始下载
                        [self downloadBtnClk];
                        self.firstDownload = NO;
                    }
                    
                    [self sendDowloadInfoData];
                    return;
                }
                NSString *tempStr = [NSString stringWithFormat:@"下载包编号%zd成功",_packetIndex];
                [self addText:tempStr];
                
                _packetIndex++;

                if (!self.isInfoDataDownloadComplete) {
                    // 发送数据块
                    [self sendDowloadInfoData];
                }else{
                    [self addText:@"数据块下载成功"];
                    
                    NSData *tempData = [GGDFUProtocol completeWithPacketIndex:self.packetIndex];
                    [[GGBLEManager getInstance] sendMsgWithSubPackage:tempData];
                    self.downloadCount++;
                    self.sendDataSuccess = NO;
                    self.previousData = tempData;
                    
                    self.step = GGDFUDownLoadStepComplete;
                }
            }
                break;
            case GGDFUDownLoadStepComplete:
            {
                // 解析返回的数据
                NSData *infoData = [GGDFUProtocol parseInfoData:responseData];
                NSUInteger packetIndex = [GGDFUProtocol parseInfoDataPacketIndex:infoData];
                BOOL isSucceed = [GGDFUProtocol parseCommandResult:infoData];
                
                if (packetIndex != _packetIndex || isSucceed == NO) {
                    [self addText:@"下载结束失败"];
                    return;
                }
                
                [self addText:@"下载成功完成"];
                self.downLoadBtn.enabled = YES;
            }
                break;
                
            default:
                break;
        }

    }];
}

- (void)sendDowloadInfoData
{
    // 发送下载文件
    NSInteger count = [_fileData length] / 1024 + 1;
    
    NSData *data = [[NSData alloc] init];
    
    if (_packetIndex == count) {
        data = [_fileData subdataWithRange:NSMakeRange(1024 * (_packetIndex - 1), [_fileData length] - 1024 * (_packetIndex - 1))];
        self.infoDataDownloadComplete = YES;
    }else{
        data = [_fileData subdataWithRange:NSMakeRange(1024 * (_packetIndex - 1), 1024)]; //截取数据
    }
    
    NSData *tempData = [GGDFUProtocol downloadWithPacketIndex:self.packetIndex infoData:data];
    [[GGBLEManager getInstance] sendMsgWithSubPackage:tempData];
    self.downloadCount++;
    self.sendDataSuccess = NO;
    self.previousData = tempData;
    [self resumeTimer];
    
//    NSLog(@"组包好的数据：%@",tempData);
}

- (void)reSendData
{
    NSLog(@"reSendData");
    if (self.downloadCount == 5) {
        [self addText:@"已下载5次都未成功，请检查xxxxx"];
        [self clearTimerAndDownloadCount];
        self.downLoadBtn.enabled = YES;
        return;
    }
    // 如果数据没有返回，则继续发送
    if (!self.isSendDataSuccess) {
//        if (self.previousData == nil) {
//            NSLog(@"上一次发送的数据为空%@",self.previousData);
//            return;
//        }
        NSLog(@"上一次发送的数据%@",self.previousData);
        [[GGBLEManager getInstance] sendMsgWithSubPackage:self.previousData];
        self.downloadCount++;
        self.sendDataSuccess = NO;
        [self addText:@"数据接收超时，重新发送"];
        
        return;
    }else{
        [self clearTimerAndDownloadCount];
    }
}

- (void)resumeTimer
{
    self.timer.fireDate = [NSDate dateWithTimeInterval:3.0f sinceDate:[NSDate date]];
//    [self.timer setFireDate:[NSDate distantPast]];
}

- (void)clearTimerAndDownloadCount
{
    // 关闭计时
    [self.timer setFireDate:[NSDate distantFuture]];
    self.downloadCount = 0;
    self.sendDataSuccess = YES;
}

#pragma mark - TextViewDelegate
// 向textview中添加数据
-(void)addText:(NSString *)text
{
    self.debugTextView.text = [self.debugTextView.text stringByAppendingFormat:@"\n%@",text];
    [self.debugTextView scrollRangeToVisible:self.debugTextView.selectedRange];
}

- (void)textViewDidChangeSelection:(UITextView *)textView
{
    if ([textView.text length] > 4000) {
        self.debugTextView.text = nil;
    }
}

@end
